package com.wison.quartz.job;

import com.wison.bean.GS;
import com.wison.bean.Xf;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.entity.Record;
import org.nutz.dao.pager.Pager;
import org.nutz.dao.sql.Sql;
import org.nutz.http.Http;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.json.Json;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/6/3.
 */
@IocBean
public class XFJob implements Job {

    @Inject
    private Dao dao;

    @Inject("java:$conf.get('server_url')")
    private String wsdlurl;


    @Inject("java:$conf.get('dwID')")
    private String dwID;


    @Inject
    private DataSource dataSource;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {


        Connection conn = null;
        try {


            conn = dataSource.getConnection();
            conn.setAutoCommit(false);
            PreparedStatement ps = conn.prepareStatement("update ty_lock set id=1 where id=1  ");
            ps.execute();

            Map<String, Object> parms = new HashMap<String, Object>();

            Sql sql = Sqls.queryRecord("select top 100 user_no bh , user_lname xm , user_card kh , 场所名称 xfdd , 交易日期 xfrq , [time] xfsj , xh dwxh , xh record , xz xz , user_serial dz , 设备编号 zdjh , 消费明细 xfje , 交易后金额 ssyje , '" + dwID + "' dw, NewID() [guid],xh from view_nt_xfmx where not exists ( select 1 from ty_xf where id = xh)");


            while (true) {
                dao.execute(sql);
                List<Record> list = sql.getList(Record.class);
                if (null == list || list.size() == 0) {
                    break;
                }

                parms.put("cards", Json.toJson(list));
                String response = Http.post(wsdlurl + "/saveXF.do", parms, 50 * 1000);
                GS gs = Json.fromJson(GS.class, response);
                if (gs.isSuccess()) {
                    for (Record r : list) {
                        dao.insert(new Xf(Integer.parseInt(r.get("xh").toString())));
                    }
                }
                System.out.println(response);
            }
            conn.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                conn.close();
            } catch (Exception e) {

            }
        }

    }
}
